# coding=UTF-8
# author=suemi
# created at 16/5/13
import datetime, traceback
from entity.BaseEntity import BaseEntity
from utils.Constants import DATETIME_FORMAT
from utils.ToolUtil import ToolUtil


class Article(BaseEntity):
    def __init__(self):
        self.url = None
        self.author = None
        self.crawledAt = None
        self.publishAt = None
        self.title = None
        self.tag = None
        self.site = None
        self.content = None
        self.lang = 'zh_cn'

    def identify(self):
        """
        生成一篇文章的唯一标识,采用爬取日期+URL MD5值的方式
        :return:
        """
        return self.crawledAt.strftime(DATETIME_FORMAT) + "_" + self.documentId()

    def documentId(self):
        return ToolUtil.md5(self.url)

    def fromJson(self, jsonstr):
        super(Article, self).fromJson(jsonstr)
        if isinstance(self.crawledAt, str) or isinstance(self.crawledAt, unicode):
            self.crawledAt = datetime.datetime.strptime(self.crawledAt, DATETIME_FORMAT)
        # try:
        #     if isinstance(self.publishAt, str) or isinstance(self.publishAt, unicode):
        #         self.publishAt = datetime.datetime.strptime(self.publishAt, DATETIME_FORMAT)
        #     elif not isinstance(self.publishAt,datetime.datetime):
        #         self.publishAt = None
        # except Exception,e:
        #     traceback.print_exc()
        #     # self.publishAt = None
        # finally:
        #     return self

        if not (isinstance(self.publishAt, str) or
                    isinstance(self.publishAt, unicode) or
                    isinstance(self.publishAt, datetime.datetime)):
            self.publishAt = None
        return self

    def toDict(self):
        """
        为了向ES提交日期类型,不得不转化成字符串
        :return:
        """
        tmp = super(Article, self).toDict()
        crawledAt = tmp.get('crawledAt', datetime.datetime.now())
        if isinstance(crawledAt, datetime.datetime):
            tmp['crawledAt'] = crawledAt.strftime(DATETIME_FORMAT)
        publishAt = tmp.get('publishAt', None)
        if isinstance(publishAt, datetime.datetime):
            tmp['publishAt'] = publishAt.strftime(DATETIME_FORMAT)
        elif not (isinstance(publishAt, str) or isinstance(self.publishAt, unicode)):
            tmp.pop("publishAt",None)

        # elif publishAt is not None:
        #     try:
        #         publishDate = datetime.datetime.strptime(publishAt, DATETIME_FORMAT)
        #     except Exception,e:
        #         tmp.pop('publishAt')
        #         traceback.print_exc()
        return tmp
